package cn.edu.zstu.qingzhu.qingzhushop.config;


import cn.edu.zstu.qingzhu.qingzhushop.handler.*;
import cn.edu.zstu.qingzhu.qingzhushop.security.CustomAccessDecisionManager;
import cn.edu.zstu.qingzhu.qingzhushop.security.CustomFilterInvocationSecurityMetadataSource;
import cn.edu.zstu.qingzhu.qingzhushop.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.AuthenticationTrustResolverImpl;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.web.filter.CorsFilter;

/**
 * @Author ShenTuZhiGang
 * @Version 1.0.0
 * @Date 2020-03-07 16:48
 */
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class CustomWebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    IUserService iUserService;
    @Autowired
    CustomFilterInvocationSecurityMetadataSource customFilterInvocationSecurityMetadataSource;
    @Autowired
    CustomAccessDecisionManager customAccessDecisionManager;
    @Autowired
    CustomAuthenticationAccessDeniedHandler customAuthenticationAccessDeniedHandler;
    @Autowired
    CustomSavedRequestAwareAuthenticationSuccessHandler customSavedRequestAwareAuthenticationSuccessHandler;
    @Autowired
    CustomAuthenticationFailureHandler customAuthenticationFailureHandler;
    @Autowired
    CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
    @Autowired
    CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
    @Autowired
    CustomLogoutSuccessHandler customLogoutSuccessHandler;

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationTrustResolver authenticationTrustResolver() {
        return new AuthenticationTrustResolverImpl();
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/**", "/index.html", "/favicon.ico",
                "/verifyCode", "/user/register",
                "/swagger**/**", "/webjars/**", "/v3/**", "/doc.html",
                "/js/**", "/css/**", "/img/**", "/fonts/**", "/images/**",
                "/qiniu/**", "/admin/**", "/goods/**", "/goodsCategory/**");
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(iUserService);
    }
    /**
     * CORS 过滤器
     */
    @Autowired
    private CorsFilter corsFilter;
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .withObjectPostProcessor(
                        new ObjectPostProcessor<FilterSecurityInterceptor>() {
                            @Override
                            public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                                object.setSecurityMetadataSource(customFilterInvocationSecurityMetadataSource);
                                object.setAccessDecisionManager(customAccessDecisionManager);
                                return object;
                            }
                        }
                )
                .and()
                .formLogin()
                //.loginPage("/login")
                .loginProcessingUrl("/doLogin")
                .usernameParameter("phone")
                .passwordParameter("password")
                .failureHandler(customAuthenticationFailureHandler)
                .successHandler(customSavedRequestAwareAuthenticationSuccessHandler)
                .permitAll()
                .and()
                .oauth2Login()
                .successHandler(customAuthenticationSuccessHandler)
                .permitAll()
                .and()
                .logout()
                .logoutSuccessHandler(customLogoutSuccessHandler)
                .permitAll()
                .and()
                .csrf()
                .disable()//CORS过滤器
                .addFilter(corsFilter)
                .exceptionHandling()
                .accessDeniedHandler(customAuthenticationAccessDeniedHandler)
                //没有认证时，在这里处理结果，不重定向
                //.authenticationEntryPoint(customAuthenticationEntryPoint)
                .defaultAuthenticationEntryPointFor(customAuthenticationEntryPoint, new AntPathRequestMatcher("/login"));
    }
}
